package com.usian.quartz;

import com.usian.config.RedisClient;
import com.usian.mapper.TbItemMapper;
import com.usian.mapper.TbOrderItemMapper;
import com.usian.mapper.TbOrderMapper;
import com.usian.mq.MQSender;
import com.usian.pojo.*;
import com.usian.service.LocalMessageService;
import com.usian.service.OrderService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

public class OrderQuartz implements Job {

    @Autowired
    private TbOrderMapper tbOrderMapper;

    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;

    @Autowired
    private TbItemMapper tbItemMapper;

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private LocalMessageService localMessageService;

    @Autowired
    private MQSender mqSender;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {


        if(redisClient.setnx("SETNX_LOCK_ORDER_KEY","1",30L)){
            //查询要关闭的超超时订单
            List<TbOrder> orderList = tbOrderMapper.selectOvertimeOrder();

            //执行关闭  update  order status  6
            for(TbOrder order :orderList){
                order.setStatus(6);
                tbOrderMapper.updateByPrimaryKeySelective(order);

                //恢复库存
                TbOrderItemExample example =new TbOrderItemExample();
                TbOrderItemExample.Criteria criteria = example.createCriteria();
                criteria.andOrderIdEqualTo(order.getOrderId());
                List<TbOrderItem> itemList = tbOrderItemMapper.selectByExample(example);
                for(TbOrderItem orderItem :itemList){
                    TbItem tbItem = tbItemMapper.selectByPrimaryKey(Long.valueOf(orderItem.getItemId()));
                    tbItem.setNum(tbItem.getNum() + orderItem.getNum());
                    tbItem.setUpdated(new Date());
                    tbItemMapper.updateByPrimaryKeySelective(tbItem);

                }
            }

            //定时扫描localmessage 表  status 为0  List   遍历   amqp 重新发送
            List<LocalMessage> list = localMessageService.selectLocalMessageByStatus();
            if(list.size()>0){
                for(LocalMessage localMessage :list){
                    mqSender.sendMsg(localMessage);
                    System.out.println("其他任务正在执行，请稍后=============================");
                }
            }
            redisClient.del("SETNX_LOCK_ORDER_KEY");
        }else{
            System.out.println("其他任务正在执行，请稍后");
        }
    }
}
